"""
题库管理模块 - API视图
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q, Count, Avg
from django.shortcuts import get_object_or_404
import pandas as pd
import json
import io
from datetime import datetime, timedelta

from .models import Question, QuestionBank, QuestionBankItem, QuestionTag
from .serializers import (
    QuestionListSerializer, QuestionDetailSerializer, QuestionCreateSerializer,
    QuestionUpdateSerializer, QuestionBankSerializer, QuestionBankDetailSerializer,
    QuestionBankCreateSerializer, QuestionBankItemSerializer,
    QuestionImportSerializer, QuestionExportSerializer,
    QuestionStatisticsSerializer, QuestionBankStatisticsSerializer
)
from .utils import QuestionImporter, QuestionExporter
from .permissions import (
    IsQuestionOwnerOrReadOnly, IsQuestionBankOwnerOrReadOnly,
    CanManageQuestionBank, CanAccessQuestionBank, CanAddQuestionsToBank,
    CanImportQuestions, CanExportQuestions, CanReviewQuestions,
    HasQuestionBankAccess
)
from common.permissions import IsOwnerOrReadOnly, IsTeacherOrAdmin


class QuestionViewSet(viewsets.ModelViewSet):
    """题目ViewSet"""
    permission_classes = [IsAuthenticated, IsQuestionOwnerOrReadOnly]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['type', 'difficulty', 'subject', 'chapter', 'status']

    def get_queryset(self):
        """根据用户权限获取题目"""
        user = self.request.user

        if user.is_admin_user:
            return Question.objects.all()
        elif user.is_teacher:
            # 教师可以查看自己的题目和公开题目
            return Question.objects.filter(
                Q(creator=user) | Q(is_public=True)
            ).distinct()
        else:
            # 学生只能查看公开的激活题目
            return Question.objects.filter(
                is_public=True,
                status='active'
            ).distinct()

    def get_serializer_class(self):
        """根据操作类型获取序列化器"""
        if self.action == 'list':
            return QuestionListSerializer
        elif self.action == 'create':
            return QuestionCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return QuestionUpdateSerializer
        return QuestionDetailSerializer

    def perform_create(self, serializer):
        """创建题目时设置创建者"""
        serializer.save(creator=self.request.user)

    def get_permissions(self):
        """根据操作类型获取权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            # 题目管理需要教师或管理员权限
            return [IsAuthenticated, IsTeacherOrAdmin]
        return super().get_permissions()

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取题目统计信息"""
        queryset = self.get_queryset()

        # 总题目数
        total_questions = queryset.count()

        # 按类型统计
        questions_by_type = dict(
            queryset.values('type').annotate(count=Count('id')).values_list('type', 'count')
        )

        # 按难度统计
        questions_by_difficulty = dict(
            queryset.values('difficulty').annotate(count=Count('id')).values_list('difficulty', 'count')
        )

        # 按科目统计
        questions_by_subject = dict(
            queryset.values('subject').annotate(count=Count('id')).values_list('subject', 'count')
        )

        # 平均正确率
        avg_correct_rate = queryset.aggregate(
            avg_rate=Avg('correct_rate')
        )['avg_rate'] or 0

        # 使用统计
        usage_stats = {
            'total_usage': queryset.aggregate(total=Count('usage_history'))['total'] or 0,
            'recent_usage': queryset.filter(
                usage_history__created_at__gte=datetime.now() - timedelta(days=30)
            ).aggregate(count=Count('usage_history'))['count'] or 0
        }

        serializer = QuestionStatisticsSerializer({
            'total_questions': total_questions,
            'questions_by_type': questions_by_type,
            'questions_by_difficulty': questions_by_difficulty,
            'questions_by_subject': questions_by_subject,
            'average_correct_rate': avg_correct_rate,
            'usage_statistics': usage_stats
        })

        return Response(serializer.data)

    @action(detail=False, methods=['post'])
    def bulk_import(self, request):
        """批量导入题目"""
        serializer = QuestionImportSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            file = serializer.validated_data['file']
            question_bank_id = serializer.validated_data['question_bank_id']
            options = serializer.validated_data.get('options', {})

            # 获取题库
            question_bank = get_object_or_404(QuestionBank, id=question_bank_id)

            # 权限检查
            if not request.user.is_admin_user and question_bank.owner != request.user:
                return Response(
                    {'error': '没有权限导入题目到此题库'},
                    status=status.HTTP_403_FORBIDDEN
                )

            # 执行导入
            importer = QuestionImporter(file, question_bank, request.user, options)
            result = importer.import_questions()

            return Response({
                'success': True,
                'data': result
            })

        except Exception as e:
            return Response({
                'success': False,
                'error': str(e)
            }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['post'])
    def bulk_export(self, request):
        """批量导出题目"""
        serializer = QuestionExportSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            question_ids = serializer.validated_data['question_ids']
            export_format = serializer.validated_data['export_format']
            include_answers = serializer.validated_data['include_answers']
            include_analysis = serializer.validated_data['include_analysis']

            # 获取题目
            questions = self.get_queryset().filter(id__in=question_ids)
            if not questions.exists():
                return Response(
                    {'error': '未找到指定的题目'},
                    status=status.HTTP_404_NOT_FOUND
                )

            # 执行导出
            exporter = QuestionExporter(questions, export_format, include_answers, include_analysis)
            file_data = exporter.export()

            # 返回文件
            from django.http import HttpResponse
            response = HttpResponse(
                file_data,
                content_type='application/octet-stream'
            )
            response['Content-Disposition'] = f'attachment; filename=questions.{export_format}'
            return response

        except Exception as e:
            return Response({
                'success': False,
                'error': str(e)
            }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def review(self, request, pk=None):
        """审核题目"""
        if not request.user.is_teacher and not request.user.is_admin_user:
            return Response(
                {'error': '没有审核权限'},
                status=status.HTTP_403_FORBIDDEN
            )

        question = self.get_object()
        action_type = request.data.get('action')  # 'approve' or 'reject'
        comment = request.data.get('comment', '')

        if action_type == 'approve':
            question.review_status = 'approved'
        elif action_type == 'reject':
            question.review_status = 'rejected'
        else:
            return Response(
                {'error': '无效的审核操作'},
                status=status.HTTP_400_BAD_REQUEST
            )

        question.reviewer = request.user
        question.review_comment = comment
        question.reviewed_at = datetime.now()
        question.save()

        return Response({
            'success': True,
            'data': {
                'review_status': question.review_status,
                'review_comment': question.review_comment,
                'reviewed_at': question.reviewed_at
            }
        })


class QuestionBankViewSet(viewsets.ModelViewSet):
    """题库ViewSet"""
    permission_classes = [IsAuthenticated, HasQuestionBankAccess]

    def get_queryset(self):
        """根据用户权限获取题库"""
        user = self.request.user

        if user.is_admin_user:
            return QuestionBank.objects.all()
        else:
            # 用户可以查看自己的题库和公开题库
            return QuestionBank.objects.filter(
                Q(owner=user) | Q(is_public=True)
            ).distinct()

    def get_serializer_class(self):
        """根据操作类型获取序列化器"""
        if self.action == 'list':
            return QuestionBankSerializer
        elif self.action == 'create':
            return QuestionBankCreateSerializer
        elif self.action == 'retrieve':
            return QuestionBankDetailSerializer
        return QuestionBankSerializer

    def perform_create(self, serializer):
        """创建题库时设置所有者"""
        serializer.save(owner=self.request.user)

    @action(detail=True, methods=['get'])
    def questions(self, request, pk=None):
        """获取题库中的题目"""
        question_bank = self.get_object()

        # 权限检查
        if not question_bank.can_access(request.user):
            return Response(
                {'error': '没有权限访问题库'},
                status=status.HTTP_403_FORBIDDEN
            )

        # 获取题目
        items = question_bank.question_items.select_related('question').filter(status='active')

        # 分页
        page = self.paginate_queryset(items)
        if page is not None:
            serializer = QuestionBankItemSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = QuestionBankItemSerializer(items, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def add_questions(self, request, pk=None):
        """向题库添加题目"""
        question_bank = self.get_object()

        # 权限检查
        if question_bank.owner != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限修改此题库'},
                status=status.HTTP_403_FORBIDDEN
            )

        question_ids = request.data.get('question_ids', [])
        custom_points = request.data.get('custom_points', {})
        custom_difficulty = request.data.get('custom_difficulty', {})

        questions = Question.objects.filter(id__in=question_ids)

        created_count = 0
        for question in questions:
            # 创建题库题目项
            item, created = QuestionBankItem.objects.get_or_create(
                question_bank=question_bank,
                question=question,
                defaults={
                    'custom_points': custom_points.get(str(question.id)),
                    'custom_difficulty': custom_difficulty.get(str(question.id)),
                    'added_by': request.user
                }
            )

            if created:
                created_count += 1

        # 更新统计信息
        question_bank.update_statistics()

        return Response({
            'success': True,
            'data': {
                'added_count': created_count,
                'total_questions': question_bank.question_count
            }
        })

    @action(detail=True, methods=['post'])
    def remove_questions(self, request, pk=None):
        """从题库移除题目"""
        question_bank = self.get_object()

        # 权限检查
        if question_bank.owner != request.user and not request.user.is_admin_user:
            return Response(
                {'error': '没有权限修改此题库'},
                status=status.HTTP_403_FORBIDDEN
            )

        question_ids = request.data.get('question_ids', [])
        deleted_count = question_bank.question_items.filter(
            question_id__in=question_ids
        ).delete()[0]

        # 更新统计信息
        question_bank.update_statistics()

        return Response({
            'success': True,
            'data': {
                'removed_count': deleted_count,
                'total_questions': question_bank.question_count
            }
        })

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取题库统计信息"""
        queryset = self.get_queryset()

        # 总题库数
        total_banks = queryset.count()

        # 按类型统计
        banks_by_type = dict(
            queryset.values('type').annotate(count=Count('id')).values_list('type', 'count')
        )

        # 总题目数
        total_questions = sum(bank.question_count for bank in queryset)

        # 平均题目数
        avg_questions = total_questions / total_banks if total_banks > 0 else 0

        # 最常用标签
        most_used_tags = dict(
            QuestionTag.objects.annotate(
                usage_count=Count('question_relations')
            ).order_by('-usage_count')[:10].values_list('name', 'usage_count')
        )

        serializer = QuestionBankStatisticsSerializer({
            'total_banks': total_banks,
            'banks_by_type': banks_by_type,
            'total_questions': total_questions,
            'average_questions_per_bank': avg_questions,
            'most_used_tags': most_used_tags,
            'recent_activity': {}  # TODO: 添加近期活动统计
        })

        return Response(serializer.data)